package com.rabbitmq.demo;

import com.rabbitmq.client.*;

import java.nio.charset.StandardCharsets;

/**
 * @ClassName ConsumerB
 * @Description 扇出交换机消费者B
 * @Author Kx
 * @Date 2025/10/10 11:19
 * @Version 1.0
 */
public class ConsumerB {
    /**
     * 声明队列
     */
    private final static String QUEUE_ONE = "queue.fanout.two";
    /**
     * 声明交换机
     */
    private final static String EXCHANGE_NAME = "my.fanout";

    /**
     * 声明工厂
     */
    private static ConnectionFactory connectionFactory;

    /**
     * 初始化工厂
     */
    static{
        connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("localhost");
        connectionFactory.setPort(5672);
        connectionFactory.setUsername("kx");
        connectionFactory.setPassword("123456");
    }

    /**
     * @author: kx
     * @date: 2025/10/10 11:07
     * @description: 接收信息
     */
    public static void receive() {
        try {
            // 创建连接
            Connection conn = connectionFactory.newConnection();
            // 创建通信
            Channel channel = conn.createChannel();
            //声明topic(主题)类型交换机
            channel.exchangeDeclare(EXCHANGE_NAME, BuiltinExchangeType.FANOUT);
            //声明队列
            channel.queueDeclare(QUEUE_ONE, false, false, false, null);
            //将交换机和队列结合路由的KEY进行绑定
            //参数三：路由的KEY
            // 绑定时，路由键可以是任意的字符串(通常是空字符串) 因为 FANOUT 会忽悠路由key
            channel.queueBind(QUEUE_ONE, EXCHANGE_NAME, "");
            //接收消息
            DeliverCallback callback = (consumerTag, delivery) -> {
                String message = new String(delivery.getBody(), StandardCharsets.UTF_8);
                System.out.println("消费者B 接收到消息：" + message);
            };
            // 订阅消息
            channel.basicConsume(QUEUE_ONE, true, callback, consumerTag -> {});
        }catch (Exception e){
            throw new RuntimeException("消费失败",e);
        }
    }

    public static void main(String[] args) {
        receive();
    }
}
